package com.ydx.meituan.config.httpClient;

import com.google.gson.Gson;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.Map;

@Component
public class HttpClientUtil {

    @Resource
    RestTemplate restTemplate;

    public   <T>  T getForm(String url, Map<String, Object> parameters, Class<T> responseType){
        String params = getKeyValueParams(parameters);
        url =url+"?"+params;
        //设置访问的Entity
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity(null, headers);
        ResponseEntity<T> result = restTemplate.exchange(url, HttpMethod.GET, requestEntity, responseType);
        return result.getBody();
    }




    public   <T>  T postForm(String url, Map<String, Object> parameters, Class<T> responseType){
        String params = getKeyValueParams(parameters);
        //设置访问的Entity
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpEntity<MultiValueMap> requestEntity = new HttpEntity(params, headers);
        ResponseEntity<T> result = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
        return result.getBody();
    }




    public   <T>  T postJson(String url, Map<String, Object> parameters, Class<T> responseType){
        String params = new Gson().toJson(parameters);
        //设置访问的Entity
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> requestEntity = new HttpEntity(params, headers);
        ResponseEntity<T> result = restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
        return result.getBody();
    }



    //转换key value形式参数
    private String getKeyValueParams(Map<String, Object> parameters){
        StringBuffer param = new StringBuffer();
        int i = 0;
        for (String key : parameters.keySet()) {
            if (i == 0){
//                param.append("?");
            }
            else
                param.append("&");
            param.append(key).append("=").append(parameters.get(key));
            i++;
        }
        return param.toString();
    }



}
